package com.primeton.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.espertech.esper.collection.Pair;
import com.espertech.esper.epl.agg.aggregator.AggregationMethod;

public class SerializerUtil {

	private static SerializerUtil util;
	private static Kryo kryo = new Kryo();
	private static final String rootDir = "/states/";
	private static final String mapName = "epl_file.map";

	public static SerializerUtil getInstance() {
		if (util == null) {
			util = new SerializerUtil();
			kryo.setReferences(false);
			kryo.register(Pair.class);
			kryo.register(AggregationMethod.class);
			kryo.register(List.class);
			kryo.register(Map.class);
			kryo.register(HashMap.class);
			kryo.register(int[].class);
		}
		return util;
	}

	public synchronized void doserialize(HashMap obj, String fileName) {
		if (obj == null || obj.size() < 1) {
			return;
		}
		FileOutputStream fos = null;
		Output output = null;
		try {
			fos = new FileOutputStream(fileName);
			output = new Output(fos);
			kryo.writeObject(output, obj);
		} catch (FileNotFoundException e) {
			System.err.println(mapName + "文件找不到！");
		} finally {
			if (output != null) {
				output.close();
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void doserializeMethodProps(HashMap stateMap, int hashcode) {
		String fileName = rootDir + hashcode;
		this.doserialize(stateMap, fileName);
	}

	public void doserializeMap(HashMap map) {
		this.doserialize(map, rootDir + mapName);
	}

	public HashMap deSerializeMap() {
		return this.deSerialize(rootDir + mapName);
	}

	public synchronized HashMap deSerialize(String fileName) {
		HashMap retVal = new HashMap();
		FileInputStream fis = null;
		Input input = null;
		try {
			fis = new FileInputStream(fileName);
			input = new Input(fis);
			retVal = kryo.readObject(input, HashMap.class);
		} catch (FileNotFoundException e) {
			System.err.println(mapName + "文件找不到！");
		} catch (KryoException e1) {
			System.err.println("文件无法反序列化");
		} finally {
			if (input != null) {
				input.close();
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return retVal;

	}
}
